package org.mspring.mlog.web.push;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Gao Youbo
 * @since 2013-4-24
 */
public class PushMessage {

    private static final Logger log = LoggerFactory.getLogger(PushMessage.class);

    private static WriterAppender wa = null;

    /**
     * push message
     *
     * @param message
     */
    public static void push(String message) {
        if (wa == null) {
            wa = new DefaultWriterAppender();
        }
        try {
            wa.writer.write(messageEscape(message));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 执行推送JS
     *
     * @param script
     */
    public static void pushScript(String script) {
        if (wa == null) {
            wa = new DefaultWriterAppender();
        }
        try {
            wa.writer.write(script);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * @param message
     * @return
     */
    private static String messageEscape(String message) {
        return "<script type='text/javascript'>window.parent.pushMessage(\"" + message.replaceAll("\n", "").replaceAll("\r", "") + "\");</script>";
    }
}
